package com.jilujia.domain.user;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.annotation.Scope;
import org.springframework.security.authentication.encoding.PasswordEncoder;
import org.springframework.security.authentication.encoding.ShaPasswordEncoder;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.jilujia.domain.user.repository.UserRepository;
import com.jilujia.framework.domain.AbstractPoEntityManager;
import com.jilujia.framework.exception.BusinessException;

@Component
@Scope(BeanDefinition.SCOPE_PROTOTYPE)
public class UserManager extends AbstractPoEntityManager<Long, User, UserRepository> {

	@Autowired
	private ShaPasswordEncoder tokenEncoder;

	@Autowired
	private PasswordEncoder passwordEncoder;

	@Transactional
	public User saveUser(User user) {
		this.setInstance(user);
		this.save();
		return user;
	}

	protected void preSave() {
		User user = this.getInstance();

		User existedSameUsernameUser = this.getRepository().findUserByUsername(user.getUsername());
		if (existedSameUsernameUser != null && !user.getId().equals(existedSameUsernameUser.getId())) {
			throw new BusinessException("Duplicate Username");
		}

		User existedSameNicknameUser = this.getRepository().findUserByNickname(user.getNickname());
		if (existedSameNicknameUser != null && !user.getId().equals(existedSameNicknameUser.getId())) {
			throw new BusinessException("Duplicate Nickname");
		}

	}

	protected void postSave() {
	}

	@Transactional
	public void validateUser(String confirmtoken) {
		User user = this.getRepository().findUserByToken(confirmtoken);
		if (user != null) {
			user.setActive(true);
			user.setEnable(true);
			this.setInstance(user);
			this.save();
		} else {
			throw new BusinessException("can't active user");
		}
	}

	@Transactional
	public void registerUser() {
		User user = this.getInstance();
		user.setPassword(passwordEncoder.encodePassword(user.getPassword(), null));
		user.setActive(false);
		user.setEnable(false);
		user.setConfirmtoken(tokenEncoder.encodePassword(user.getUsername(), "jilujiasalt"));
		this.save();

	}

}
